<template>
  <div class="flex" style="margin-bottom: 0px;">
    <div class="play_item">
      <img :src="audioStatus" alt style class="audio_player_item" @click="playPauseAudio" />
    </div>
    <div class="flex_item">
      <div style class="audio_content_layer" ref="audio_content_layer">
        <audio
          ref="audio"
          preload="auto"
          :src="audioUrl"
          @ended="onended"
          @play="onplay"
          @pause="onpause"
          @error="onerror"
          @timeupdate="ontimeupdate"
          @loadedmetadata="onloadedmetadata"
        ></audio>
        <el-progress :percentage="audioProgressPercentage" :show-text="false"></el-progress>
        <img
          :src="audioIconCircle"
          :style="pointStyle"
          class="audio_timer_point"
          @mousedown.prevent="pointMouseDown"
        />
        <div class="progress_info_layer">
          <div style="display: inline-block;float: left;">{{currentPlayTimeStr}}</div>
          <div style="display: inline-block;float: right;">{{audioDurationStr}}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    name: "AudioPlayer",
    props: {
      url: {
        type: String,
      },
    },
    data() {
      return {
        pointStyle: { left: "0%" },
        audioStatus: "",
        audioIconPlay: require("@/assets/icons/start.png"), //播放
        audioIconPause: require("@/assets/icons/pause.png"), //暂停
        audioIconCircle: require("@/assets/icons/circle.png"), //播放进度圆点
        audioProgressPercentage: 0, //播放进度百分比
        audioDuration: 0, // 音频的时长（秒）
        audioDurationStr: "00:00",
        currentPlayTimeStr: "00:00",
        // 当前的播放进度百分比，0~100;
        currentPercent: 0,

        // 鼠标是否按下小圆点（调整播放进度）
        isMouseDown: false,
        // 鼠标按下小圆点时的播放进度百分比
        mouseDownPercent: 0,
        // 鼠标移动过程中的播放进度百分比
        mouseMovePercent: 0,
        // 鼠标按下时的屏幕坐标
        mouseDownPageX: 0,
        // 鼠标按下时的小圆点容器宽度
        mouseDownLayerWidth: 0,
      };
    },
    computed:{
      audioUrl(){
        return this.url;
      }
    },
    created() {
      this.audioStatus = this.audioIconPlay;
      // this.audioUrl = require("@/assets/audio/demo.mp3");
      // this.audioUrl = "";
      window.addEventListener( "mouseup", (e)=>{
        this.pointMouseUp(e);
      })
      window.addEventListener( "mousemove", (e)=>{
        this.pointMouseMove(e);
      })
    },

    methods: {
      stop(){
        this.$refs.audio.pause();
        this.$refs.audio.currentTime = 0;
        this.setCurrentPlayPercent(0);
      },
      play(){
        this.$refs.audio.play();
      },
      // 开始或停止音频播放
      playPauseAudio() {
        if (this.$refs.audio.paused) {
          this.$refs.audio.play();
        } else {
          this.$refs.audio.pause();
        }
      },
      // 设置当前的播放位置和时长，同时组装用于显示的字串
      setTimeInfo(currentTime, duration) {
        if (currentTime != null) {
          this.currentPlayTimeStr = this.getTimeBySeconds(currentTime);
        }
        if (duration != null) {
          this.audioDurationStr = this.getTimeBySeconds(duration);
          this.audioDuration = duration;
        }
      },
      // 根据秒数，得到时分秒的字串
      getTimeBySeconds(sec) {
        let strs = [];
        sec = parseInt(sec);
        if (isNaN(sec)) {
          return "00:00";
        }
        // let seconds = sec - ( Math.floor(sec / 60) * 60);
        let seconds = sec % 60;
        let minutes = Math.floor(sec / 60) % 60;
        let hours = Math.floor(sec / 3600);
        if (hours > 0) {
          strs.push(hours);
        }
        strs.push(this.getDoubleNumStr(minutes));
        strs.push(this.getDoubleNumStr(seconds));
        return strs.join(":");
      },
      getDoubleNumStr(num) {
        return (num < 10 ? "0" : "") + num;
      },
      // 当音频加载了时长数据
      onloadedmetadata(e) {
        // console.log("音频读取完成", e, this.$refs.audio, this.$refs.audio.duration);
        // this.audioDuration = this.$refs.audio.duration;
        this.setTimeInfo(null, this.$refs.audio.duration);
      },
      // 音频播放完
      onended() {
        // console.log("audio ended");
        this.audioStatus = this.audioIconPlay;
        this.setCurrentPlayPercent(0);
      },
      // 音频暂停
      onpause() {
        // console.log("audio pause");
        this.audioStatus = this.audioIconPlay;
      },
      // 音频播放
      onplay() {
        // console.log("audio play");
        this.audioStatus = this.audioIconPause;
      },
      // 音频播放进度
      ontimeupdate(e) {
        let currentTime = this.$refs.audio.currentTime;
        this.setCurrentPlayPercent(currentTime);
      },
      // 当音频播放出错时
      onerror( e){
        console.error( "音频播放出错", e);
        // this.msgError( "音频播放失败");
      },
      setCurrentPlayPercent(currentTime) {
        let percent = (currentTime / this.audioDuration) * 100;
        if( isNaN(percent)) {
          percent = 0;
        }
        this.currentPercent = percent;
        this.audioProgressPercentage = percent;
        if (!this.isMouseDown) {
          this.pointStyle.left = percent + "%";
        }
        this.setTimeInfo(currentTime, null);
      },

      // 小圆点鼠标按下
      pointMouseDown(e) {
        // console.log("mouse down", e);
        this.mouseDownPercent = this.currentPercent;
        this.mouseDownPageX = e.pageX;
        this.mouseDownLayerWidth = this.$refs.audio_content_layer.offsetWidth;
        this.isMouseDown = true;
      },
      // 小圆点鼠标松开
      pointMouseUp(e) {
        if( !this.isMouseDown) return;

        e.cancelBubble = true;
        e.stopPropagation();
        this.isMouseDown = false;
        let percent = this.mouseMovePercent;
        let currentTime = this.audioDuration * ( percent / 100);
        // console.log( "up is mouse down false", currentTime, percent);
        if( !isNaN(currentTime)){
          this.$refs.audio.currentTime = currentTime;
        }
      },
      // 小圆点鼠标松开
      pointMouseMove(e) {
        if (!this.isMouseDown) return;
        e.cancelBubble = true;
        e.stopPropagation();
        let pageX = e.pageX;
        let moveX = pageX - this.mouseDownPageX;
        let percentChange = (moveX / this.mouseDownLayerWidth) * 100 ;
        let moveEndPercent = this.mouseDownPercent + percentChange;
        // console.log( "on mouse move", moveX, percentChange, moveEndPercent);
        moveEndPercent = Math.max(0, Math.min(100, moveEndPercent));
        this.mouseMovePercent = moveEndPercent;
        this.pointStyle.left = moveEndPercent + "%";
      },
    },
  };
</script>


<style scoped lang="scss">
::v-deep {
  .el-progress-bar__outer {
    border-radius: 0;
    background-color: white;
    border: solid 1px #d0d5da;
    height: 4px !important;
    top: 0px;
  }
  .el-progress-bar__inner {
    position: absolute;
    left: 0;
    height: 100%;
    // background-color: #b0aeae;
    text-align: right;
    line-height: 1;
    width: 20px;
    border-radius: 0;
    transition: none;
  }
}

.flex {
  display: flex;
  height: 40px;
  padding: 5px;
  box-sizing: border-box;

  .play_item {
    width: 50px;
    text-align: center;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .flex_item {
    flex: 10;
  }
}
.audio_player_item {
  /*播放按钮*/
  background-color: white;
  border-radius: 12px;
  width: 26px;
  height: 26px;
  cursor: pointer;
}
.audio_timer_point {
  /*进度圆点*/
  position: absolute;
  top: 2px;
  left: 0px;
  background-color: #d0d5da;
  border-radius: 10px;
  width: 18px;
  height: 18px;
}

.audio_content_layer {
  position: relative;
  width: 100%;
  height: 100%;
  padding-top: 10px;
  box-sizing: border-box;
}

.progress_info_layer {
  margin: 6px 0px 0px 0px;
  padding: 0;
  border: 0;
  position: relative;
  top: 0px;
  font-size: 10px;
  line-height: 16px;
}
#audioIconCircle {
  cursor: pointer;
}
</style>
